//
//  AddLocationViewController.m
//  MagazineShangejie
//
//  Created by cnbizMedia on 16/4/26.
//  Copyright © 2016年 CnbizMedia. All rights reserved.
//

#import "AddLocationViewController.h"
#import "Util.h"
@implementation AddLocationViewController{


    __weak IBOutlet UIView *cityView;
    
    __weak IBOutlet UIView *chocseCityView;
    
    __weak IBOutlet UIButton *city1;
    
    __weak IBOutlet UIButton *city2;
    
    __weak IBOutlet UIButton *city3;
    
    __weak IBOutlet UIButton *city4;
    
    __weak IBOutlet UITableView *cityTableView;
    
    
    __weak IBOutlet UITextField *manName;
    
    __weak IBOutlet UITextField *phoneNumber;
    
    __weak IBOutlet UITextField *whiceBlied;
    
    __weak IBOutlet UILabel *whiceCity;
    
    __weak IBOutlet UIButton *pushLocationButton;
    
    __weak IBOutlet UISwitch *moren;
    
    
    NSMutableArray *allCityArray;
    
    NSInteger cityAryCount;
    NSInteger whiceCityBtn;
    
    
    NSInteger touchWhiceCity1;
    NSInteger touchWhiceCity2;
    NSInteger touchWhiceCity3;
    NSInteger touchWhiceCity4;
    
    NSString *locationString;
    NSString *newCityString;
    
//    province	数字	省
    NSString *province;
    //    city	数字	市
    NSString *city;
    //    county	数字	区
    NSString *county;
    
    
    NSString *status;
}

-(void)viewDidLoad{

    [super viewDidLoad];
    cityView.hidden = YES;
    chocseCityView.hidden = YES;
    allCityArray    = [[NSMutableArray alloc] init];
    locationString  = [[NSString alloc] init];
    newCityString   = [[NSString alloc] init];
    city2.userInteractionEnabled = NO;
    city3.userInteractionEnabled = NO;
    city4.userInteractionEnabled = NO;
    
    //    province	数字	省
    province = [[NSString alloc] init];
    //    city	数字	市
    city = [[NSString alloc] init];
    //    county	数字	区
    county = [[NSString alloc] init];
    county = @"0";
    
    whiceCityBtn = 1;
    cityAryCount = 0;
    status = @"1";
    
    [self loadCityNameArray];
    
    [self writeTheBlankSpace];
    
}

-(void)writeTheBlankSpace{
    //该接口必须传入action参数用来判断所需操作(add=添加=0,edit=编辑=1,delete=删除)
    if ([UserDefaults integerForKey:@"add_edit"] == 0) {
    
    }
    
    else {
      NSDictionary *aPlace = [UserDefaults objectForKey:@"aPlace"];
        
        manName.text = aPlace[@"consignee"];
        
        phoneNumber.text = aPlace[@"mobile"];
        
        whiceBlied.text = aPlace[@"full_address"];
        
        whiceCity.text = aPlace[@"full_address"];
    }
}

-(void)loadCityNameArray{

    [[AppAPIClient sharedClient] GET:@"Shop/Province" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *user = responseObject[@"data"];
        NSLog(@"user ----- %@",user);
        if (![(NSDictionary *)user isEqual: [NSNull null] ] ) {
            
            allCityArray = user[@"content"];
            cityAryCount = allCityArray.count;
            [cityTableView reloadData];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

- (IBAction)showCityView:(id)sender {
    cityView.hidden = NO;
    chocseCityView.hidden = NO;
}

- (IBAction)hiddenCityView:(id)sender {
    
    cityView.hidden = YES;
    chocseCityView.hidden = YES;
    whiceCity.text = locationString;
}

//四个城市的按钮
- (IBAction)cityEvent1:(id)sender {
    
    city2.userInteractionEnabled = YES;
    city3.userInteractionEnabled = NO;
    city4.userInteractionEnabled = NO;

    whiceCityBtn = 1;
    
    cityAryCount = allCityArray.count;
    [cityTableView reloadData];
    
    [city2 setTitle:@"" forState:UIControlStateNormal];
    [city3 setTitle:@"" forState:UIControlStateNormal];
    [city4 setTitle:@"" forState:UIControlStateNormal];
}

- (IBAction)cityEvent2:(id)sender {
    
    city3.userInteractionEnabled = YES;
    city4.userInteractionEnabled = NO;
    
    whiceCityBtn = 2;
    
    NSMutableDictionary *aCityDic = [[NSMutableDictionary alloc] init];
    aCityDic = allCityArray[touchWhiceCity1];
    
    
    NSMutableArray *aCityAry = [[NSMutableArray alloc] init];
    aCityAry = aCityDic[@"province"][@"cities"];
    NSLog(@"aCityAry %@",aCityAry);
    
    cityAryCount = aCityAry.count;
    [cityTableView reloadData];
    
    [city3 setTitle:@"" forState:UIControlStateNormal];
    [city4 setTitle:@"" forState:UIControlStateNormal];
}

- (IBAction)cityEvent3:(id)sender {
    city4.userInteractionEnabled = YES;
    
    whiceCityBtn = 3;
    
    
    NSMutableDictionary *aCityDic = [[NSMutableDictionary alloc] init];
    aCityDic = allCityArray[touchWhiceCity1];
    
    
    NSMutableArray *aCityAry = [[NSMutableArray alloc] init];
    aCityAry = aCityDic[@"province"][@"cities"];
    
    NSMutableDictionary *townDic = aCityAry[touchWhiceCity2];
    
    NSMutableArray *townAry = townDic[@"counties"];
    NSLog(@"townAry %@",townAry);
    
    cityAryCount = townAry.count;
    [cityTableView reloadData];
}

- (IBAction)cityEvent4:(id)sender {
    
    whiceCityBtn = 4;
    
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //#warning Incomplete method implementation.
    //     Return the number of rows in the section.
    
    return cityAryCount;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return 45;
    
}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if (section==0) {
//        //
//        
//        return 15;
//     
//        //        return 10;
//    }else{
//        return 15;
//    }
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell ;
  
    cell = [tableView dequeueReusableCellWithIdentifier:@"cityNameCell" forIndexPath:indexPath];

    if (cell==nil) {
       
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cityNameCell"];
        
    }
    
    NSString *aCityString = [[NSString alloc]init];
    
    if (whiceCityBtn == 1) {
        
        NSDictionary *aCityDic = allCityArray[indexPath.row];
        aCityString = aCityDic[@"province"][@"name"];
        
    }
    
    if (whiceCityBtn == 2) {
        NSLog(@"touchWhiceCity1 %ld",(long)touchWhiceCity1);
        NSDictionary *aCityDic = allCityArray[touchWhiceCity1];
        NSLog(@"第二列 aCityDic %@",aCityDic);
        NSArray *aCityArray = aCityDic[@"province"][@"cities"];
 
        NSLog(@"第二列 aCityArray %@",aCityArray);
        NSDictionary *aCityNameDic = aCityArray[indexPath.row];
        NSLog(@"第二列 aCityNameDic %@",aCityNameDic);
        aCityString = aCityNameDic[@"name"];
        NSLog(@"第二列 CityString %@",aCityString);
    }
    
    if (whiceCityBtn == 3) {
        NSDictionary *aCityDic = allCityArray[touchWhiceCity1];
        NSMutableArray *aCityArray = aCityDic[@"province"][@"cities"];
        NSDictionary *aCityNameDic = aCityArray[touchWhiceCity2];
        NSArray *townArray = aCityNameDic[@"counties"];
        NSString *aBigCityString = townArray[indexPath.row];
        NSLog(@"aBigCityString %@",aBigCityString);
        
        NSArray *array = [aBigCityString componentsSeparatedByString:@"_"]; //从字符A中分隔成2个元素的数组
        
        aCityString = array[1];
        NSLog(@"aCityString:%@",aCityString); //结果是adfsfsfs和dfsdf
        
    }
    
    if (whiceCityBtn == 4) {
        
    }
    
       UILabel*label=(UILabel*)[cell.contentView viewWithTag:11];
       label.text = aCityString;
    newCityString = aCityString;
       return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
 
    NSString *text = [[NSString alloc]init];
    
   if (cell){
     
        UILabel *textLabel = [cell viewWithTag:11];
        
        text = textLabel.text;//将2个字符串传给要跳转的控制器
     
    }
    
    //    province	数字	省
    //    city	数字	市
    //    county	数字	区
    
    if (whiceCityBtn == 1) {
        touchWhiceCity1 = indexPath.row;
        
        [city1 setTitle:text forState:UIControlStateNormal];
        
        NSDictionary *aCityDic = allCityArray[indexPath.row];
        province = aCityDic[@"province"][@"id"];
 
        
//        NSMutableDictionary *aCityDic = [[NSMutableDictionary alloc] init];
//        aCityDic = allCityArray[touchWhiceCity1];
        
        
        NSMutableArray *aCityAry = [[NSMutableArray alloc] init];
        aCityAry = aCityDic[@"province"][@"cities"];
        NSLog(@"aCityAry %@",aCityAry);
        
        cityAryCount = aCityAry.count;
        [cityTableView reloadData];
        
        locationString = [NSString stringWithFormat:@"%@",[city1 currentTitle] ];
    }
    
    if (whiceCityBtn == 2) {
        touchWhiceCity2 = indexPath.row;
        [city2 setTitle:text forState:UIControlStateNormal];
        
        
        NSMutableDictionary *aCityDic = [[NSMutableDictionary alloc] init];
        aCityDic = allCityArray[touchWhiceCity1];
        
        city = aCityDic[@"province"][@"id"];
        
        NSMutableArray *aCityAry = [[NSMutableArray alloc] init];
        aCityAry = aCityDic[@"province"][@"cities"];
        
        NSMutableDictionary *townDic = aCityAry[touchWhiceCity2];
        NSMutableArray *townAry = townDic[@"counties"];
        NSLog(@"townAry %@",townAry);
        
        cityAryCount = townAry.count;
        [cityTableView reloadData];
        
        locationString = [NSString stringWithFormat:@"%@%@",[city1 currentTitle],[city2 currentTitle]];

    }
    
    if (whiceCityBtn == 3) {
        touchWhiceCity3 = indexPath.row;
        [city3 setTitle:text forState:UIControlStateNormal];
        
        
        NSDictionary *aCityDic = allCityArray[touchWhiceCity1];
        
        NSMutableArray *aCityArray = aCityDic[@"province"][@"cities"];
        NSDictionary *aCityNameDic = aCityArray[touchWhiceCity2];
        NSArray *townArray = aCityNameDic[@"counties"];
        NSString *aBigCityString = townArray[indexPath.row];
        NSLog(@"aBigCityString %@",aBigCityString);
        
        NSArray *array = [aBigCityString componentsSeparatedByString:@"_"]; //从字符A中分隔成2个元素的数组
        
        county = array[1];
        NSLog(@" county :%@",county); //结果是adfsfsfs和dfsdf

        

        
        locationString = [NSString stringWithFormat:@"%@%@%@",[city1 currentTitle],[city2 currentTitle],[city3 currentTitle]];
        
//        NSMutableDictionary *aCityDic = [[NSMutableDictionary alloc] init];
//        aCityDic = allCityArray[touchWhiceCity1];
//        
//        
//        NSMutableArray *aCityAry = [[NSMutableArray alloc] init];
//        aCityAry = aCityDic[@"province"][@"cities"];
//        
//        NSMutableDictionary *townDic = aCityAry[touchWhiceCity2];
//        
//        NSMutableArray *townAry = townDic[@"counties"];
//        NSLog(@"townAry %@",townAry);
//        
//        cityAryCount = townAry.count;
    }
    
    if (whiceCityBtn == 4) {
        touchWhiceCity4 = indexPath.row;
        [city4 setTitle:text forState:UIControlStateNormal];
        
    }
    
    
    
    NSLog(@"locationString ==++ %@",locationString);
 
    
    ++whiceCityBtn;//点击cell后，数字自加
    
    [cityTableView reloadData];
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{



    [manName resignFirstResponder];
    
    [phoneNumber resignFirstResponder];
    
    [whiceBlied resignFirstResponder];
}


- (IBAction)moren:(id)sender {
    BOOL isButtonOn = [moren isOn];
    if (isButtonOn) {
        status = @"1";
    }else {
        status = @"0";
    }
}

- (IBAction)pushTheLocation:(id)sender {
  
    if (manName.text.length == 0) {
         [SVProgressHUD showErrorWithStatus:@"请填写用户姓名"];
        return;
    }
    
    if (whiceBlied.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写详细地址"];
        return;
    }
    
    if (whiceCity.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写详细地址"];
        return;
    }
    
    if (![CommonHelper isValidatePhone:phoneNumber.text]) {
        [SVProgressHUD showErrorWithStatus:@"您输入的号码有误!"];
        return;
    }
    
    
    
//    action	字符串	add/edit/delete
//    token	字符串	用户登录token
//    consignee	字符串	收货人
//    province	数字	省
//    city	数字	市
//    county	数字	区
//    full_address	字符串	详细地址
//    mobile	数字	联系电话
//    status	数字	是否默认收货地址(0=否,1=是)
    
    NSString *action = [[NSString alloc] init];
    //该接口必须传入action参数用来判断所需操作(add=添加=0,edit=编辑=1,delete=删除)
    if ([UserDefaults integerForKey:@"add_edit"] == 0) {
        action = @"add";
        
        
        NSLog(@"action =  %@",action );
        
        NSString *token = [UserDefaults objectForKey:@"token"];
        
        [[AppAPIClient sharedClient] POST:@"Shop/ChangeAddress" parameters:@{@"action": action,@"token":token,@"consignee":manName.text,@"province":province,@"city":city,@"county":county,@"full_address":whiceBlied.text,@"mobile":phoneNumber.text,@"status":status} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject [@"code"] integerValue] == 1) {
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"保存失败"];
            NSLog(@"Log:%@",operation.responseString);
        }];

    }
    
    else {
        action = @"edit";
        NSDictionary *aPlace = [UserDefaults objectForKey:@"aPlace"];
        
        NSLog(@"aPlace =  %@",aPlace );
        
        
        NSString *token = [UserDefaults objectForKey:@"token"];
        
        [[AppAPIClient sharedClient] POST:@"Shop/ChangeAddress" parameters:@{@"action": action,@"token":token,@"consignee":manName.text,@"province":province,@"city":city,@"county":county,@"full_address":whiceBlied.text,@"mobile":phoneNumber.text,@"status":status,@"id":aPlace[@"id"]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject [@"code"] integerValue] == 1) {
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"保存失败"];
            NSLog(@"Log:%@",operation.responseString);
        }];

    }
    
    
}

@end
